package com.lv.suyiyong.hfrwork.ui

import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ActivityUtils
import com.lv.common.base.BaseActivity
import com.lv.common.dialog.SwipeCatpchaDialog
import com.lv.common.imp.OnDialogSureListener
import com.lv.common.ktx.setSafeListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.*
import com.lv.service.bean.UserInfoOld
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.CompanyReqBody
import com.lv.service.net.SendCodeBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.room.company.CompanyDbHelper
import com.lv.service.room.company.CompanyItemBean
import com.lv.suyiyong.hfrwork.R
import com.lv.suyiyong.hfrwork.databinding.ActivityChangePhoneNextBinding
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.interfaces.TUICallback
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import okhttp3.RequestBody
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/5/6 10:33 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：修改手机号 提交
 */
@Route(path = ARoutUtils.ChangePhoneNextActivity)
class ChangePhoneNextActivity : BaseActivity<ActivityChangePhoneNextBinding>(),
    View.OnClickListener {
    @Autowired(name = "userinfo")
    @JvmField
    var mUserInfo: UserInfo? = null

    @Autowired(name = "companyInfo")
    @JvmField
    var mCompanyInfo: CompanyItemBean? = null
    private var timer: TimerUnit? = null
    private val mEditorViewModel by viewModels<EditorViewModel>()
    private val serviceViewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.activity_change_phone_next
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            vm = mEditorViewModel
            StatusBarUtil.setHeightAndPadding(this@ChangePhoneNextActivity, titleBar)
            titleBar.onClickBackIcon { finish() }
            titleBar.setTitle("修改手机号")
            tvCode.setOnClickListener(this@ChangePhoneNextActivity)
            btnLogin.setSafeListener {
                val mPhone = etPhone.text.toString().trim()
                val mCode = etCode.text.toString().trim()
                startLoading()
                lifecycleScope.launchWhenCreated {
                    this.launch {
                        if (mUserInfo != null) {
                            val result: DataResult<BaseYgxRsp> =
                                myScope.async {
                                    val partMap = mutableMapOf<String, RequestBody>()
                                    partMap["phone"] =
                                        YgxNetUtilsKt.partToRequestBody(mPhone)
                                    partMap["checkCode"] = YgxNetUtilsKt.partToRequestBody(mCode)
                                    serviceViewModel.updateMyMessage(
                                        partMap
                                    )

                                }.await()
                            parseResult(result)
                        } else {
                            val result: DataResult<BaseYgxRsp> =
                                myScope.async {
                                    serviceViewModel.updatePasswordOrPhone(
                                        CompanyReqBody(
                                            mCompanyInfo?.id ?: "",
                                            "",
                                            mPhone,
                                            mCode
                                        )
                                    )
                                }.await()
                            parseCompanyResult(result)
                        }
                    }
                }

            }
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<UserInfoOld> { code, data, message, result ->
                if (code == "200") {

                    UserDbHelper.deleteUserInfo(this@ChangePhoneNextActivity)
                    //清除Token
                    YgxUtilsKt.setAppToken("", "", "")

                    TUILogin.logout(object : TUICallback() {
                        override fun onSuccess() {
                        }

                        override fun onError(errorCode: Int, errorMessage: String?) {
                        }
                    })
                    ActivityUtils.finishAllActivities()
                    ARouter.getInstance().build(ARoutUtils.LoginActivityURL).navigation()

                    message?.let { message ->
                        showToast(this@ChangePhoneNextActivity, message)
                    }

                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
    }

    private fun parseCompanyResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<CompanyItemBean> { code, data, message, result ->
                if (code == "200") {
                    data?.let {
                        val mPhone = mBinding.etPhone.text.toString().trim()
                        mCompanyInfo?.phone = mPhone
                        CompanyDbHelper.UpDataCompany(this@ChangePhoneNextActivity, mCompanyInfo!!)
                        finish()
                    }
                    message?.let { message ->
                        showToast(this@ChangePhoneNextActivity, message)
                    }

                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
    }

    override fun initConfig() {
        super.initConfig()


    }


    override fun initData() {
        super.initData()

    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tv_code -> {
                val mPhone = mBinding.etPhone.text.toString().trim()
                if (mPhone.length == 11) {
                    showSwipecaptDialog(mPhone)
                } else {
                    showToast("新手机号有误")
                }

            }
        }
    }

    private fun showSwipecaptDialog(phone: String) {
        val swipeCatpchaDialog =
            SwipeCatpchaDialog(this, true, true, object : OnDialogSureListener {
                override fun onSureClick(content: String?) {
                    val sendCode = YgxUtilsKt.sendCode(phone)
                    startLoading()
                    lifecycleScope.launchWhenCreated {
                        this.launch {
                            val result: DataResult<BaseYgxRsp> =
                                myScope.async {
                                    if (mUserInfo != null) {
                                        serviceViewModel.sendCode(
                                            SendCodeBody(
                                                phone, sendCode, "1"
                                            )
                                        )
                                    } else {
                                        serviceViewModel.sendCodeCom(
                                            SendCodeBody(
                                                phone, sendCode, "1"
                                            )
                                        )
                                    }

                                }.await()
                            parseSendCodeResult(result)
                        }
                    }
                }
            })
        swipeCatpchaDialog.show()
    }

    private fun parseSendCodeResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<Any> { code, data, message, result ->
                if (code == "200") {
                    if (timer == null) {
                        timer = TimerUnit(mBinding.tvCode)
                    }
                    timer?.startTime()
                    message?.let { message ->
                        showToast(this@ChangePhoneNextActivity, message)
                    }
                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
    }


}